const fs = require('fs');
const path = require('path');
const archiver = require('archiver');

// 数据存储目录
const DATA_DIR = path.join(__dirname, '../survey_data');
const REPORT_DIR = path.join(__dirname, '../@data');

// 确保数据目录存在
if (!fs.existsSync(DATA_DIR)) {
    fs.mkdirSync(DATA_DIR, { recursive: true });
}

// 确保@data目录存在
if (!fs.existsSync(REPORT_DIR)) {
    fs.mkdirSync(REPORT_DIR, { recursive: true });
}

// 保存问卷数据
function saveSurvey(req, res) {
    try {
        const surveyData = req.body;
        const surveyId = surveyData.surveyId;

        // 创建问答编号对应的文件夹
        const groupDir = path.join(DATA_DIR, surveyId);
        if (!fs.existsSync(groupDir)) {
            fs.mkdirSync(groupDir, { recursive: true });
        }

        // 生成文件名
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
        const filename = `${surveyData.patientName}_${timestamp}.json`;
        const filepath = path.join(groupDir, filename);

        // 保存数据
        fs.writeFileSync(filepath, JSON.stringify(surveyData, null, 2), 'utf8');

        console.log(`问卷数据已保存: ${filepath}`);
        res.json({ success: true, message: '数据保存成功' });
    } catch (error) {
        console.error('保存问卷数据失败:', error);
        res.status(500).json({ success: false, message: '保存失败' });
    }
}

// 导出问卷数据
function exportSurvey(req, res) {
    try {
        const { surveyId, password, options } = req.body;

        // 验证密码
        const correctPassword = 'admin123'; // 实际应该从配置文件或数据库获取
        if (password !== correctPassword) {
            return res.status(401).json({ success: false, message: '密码错误' });
        }

        const groupDir = path.join(DATA_DIR, surveyId);

        // 检查目录是否存在
        if (!fs.existsSync(groupDir)) {
            return res.status(404).json({ success: false, message: '没有找到该问答编号的数据' });
        }

        // 读取所有问卷文件
        const files = fs.readdirSync(groupDir).filter(file => file.endsWith('.json'));

        if (files.length === 0) {
            return res.status(404).json({ success: false, message: '该问答编号下没有问卷数据' });
        }

        // 创建压缩包
        const archive = archiver('zip', { zlib: { level: 9 } });
        const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-');

        res.setHeader('Content-Type', 'application/zip');
        res.setHeader('Content-Disposition', `attachment; filename="问卷数据_${surveyId}_${timestamp}.zip"`);

        archive.pipe(res);

        // 生成汇总报告
        const surveys = files.map(file => {
            const content = fs.readFileSync(path.join(groupDir, file), 'utf8');
            return JSON.parse(content);
        });

        const summaryReport = generateSummaryReport(surveys, surveyId);
        archive.append(summaryReport, { name: '汇总报告.txt' });

        // 生成详细数据CSV
        const csvData = generateCSVData(surveys);
        archive.append(csvData, { name: '详细数据.csv' });

        // 如果选择包含原始数据，添加每个问卷的JSON文件
        if (options.includeRawData) {
            files.forEach(file => {
                const filepath = path.join(groupDir, file);
                archive.file(filepath, { name: `原始数据/${file}` });
            });
        }

        // 如果选择包含个人报告，生成每个人的详细报告
        if (options.includeRawData && surveys.length <= 10) {
            surveys.forEach((survey, index) => {
                const individualReport = generateIndividualReport(survey);
                archive.append(individualReport, { name: `个人报告/个人报告_${index + 1}_${survey.patientName}.txt` });
            });
        }

        archive.finalize();

    } catch (error) {
        console.error('导出失败:', error);
        res.status(500).json({ success: false, message: '导出失败' });
    }
}

// 生成汇总报告
function generateSummaryReport(surveys, surveyId) {
    const timestamp = new Date().toLocaleString('zh-CN');
    const total = surveys.length;

    // 统计分析
    let frail = 0, prefrail = 0, healthy = 0;
    let totalAge = 0, totalBMI = 0;
    let maleCount = 0, femaleCount = 0;
    let weightLoss = 0, walkTimeAbnormal = 0, gripStrengthLow = 0, activityLow = 0, fatigue = 0;

    surveys.forEach(survey => {
        // 诊断统计
        if (survey.diagnosis === '衰弱综合征') frail++;
        else if (survey.diagnosis === '衰弱前期') prefrail++;
        else healthy++;

        // 基本信息统计
        totalAge += survey.age;
        const bmi = survey.weight / Math.pow(survey.height / 100, 2);
        totalBMI += bmi;

        if (survey.gender === 'male') maleCount++;
        else femaleCount++;

        // 各项目统计
        if (survey.weightLoss === 'yes') weightLoss++;

        // 行走时间异常判断
        let walkTimeAbnormal_flag = false;
        if (survey.gender === 'male') {
            walkTimeAbnormal_flag = (survey.height <= 173 && survey.walkTime >= 7) || (survey.height > 173 && survey.walkTime >= 6);
        } else {
            walkTimeAbnormal_flag = (survey.height <= 159 && survey.walkTime >= 7) || (survey.height > 159 && survey.walkTime >= 6);
        }
        if (walkTimeAbnormal_flag) walkTimeAbnormal++;

        // 握力不足判断
        let gripStrengthLow_flag = false;
        if (survey.gender === 'male') {
            if (bmi <= 24.0) gripStrengthLow_flag = survey.gripStrength <= 29;
            else if (bmi <= 26.0) gripStrengthLow_flag = survey.gripStrength <= 30;
            else if (bmi <= 28.0) gripStrengthLow_flag = survey.gripStrength <= 30;
            else gripStrengthLow_flag = survey.gripStrength <= 32;
        } else {
            if (bmi <= 23.0) gripStrengthLow_flag = survey.gripStrength <= 17;
            else if (bmi <= 26.0) gripStrengthLow_flag = survey.gripStrength <= 17.3;
            else if (bmi <= 29.0) gripStrengthLow_flag = survey.gripStrength <= 18;
            else gripStrengthLow_flag = survey.gripStrength <= 21;
        }
        if (gripStrengthLow_flag) gripStrengthLow++;

        // 体力活动不足
        const activityThreshold = survey.gender === 'male' ? 383 : 270;
        if (survey.physicalActivity < activityThreshold) activityLow++;

        // 疲乏
        if (parseInt(survey.fatigue1) >= 2 || parseInt(survey.fatigue2) >= 2) fatigue++;
    });

    return `Fried衰弱评估数据汇总报告
问答编号：${surveyId}
导出时间：${timestamp}
问卷总数：${total}份

=== 统计分析 ===
衰弱综合征：${frail}份 (${((frail / total) * 100).toFixed(1)}%)
衰弱前期：${prefrail}份 (${((prefrail / total) * 100).toFixed(1)}%)
无衰弱健康老人：${healthy}份 (${((healthy / total) * 100).toFixed(1)}%)

平均年龄：${(totalAge / total).toFixed(1)}岁
男性：${maleCount}份，女性：${femaleCount}份
平均BMI：${(totalBMI / total).toFixed(1)}

各项目阳性率：
- 体重下降：${((weightLoss / total) * 100).toFixed(1)}%
- 行走时间异常：${((walkTimeAbnormal / total) * 100).toFixed(1)}%
- 握力不足：${((gripStrengthLow / total) * 100).toFixed(1)}%
- 体力活动不足：${((activityLow / total) * 100).toFixed(1)}%
- 疲乏：${((fatigue / total) * 100).toFixed(1)}%

=== 评分标准 ===
• 具备5条中3条及以上：衰弱综合征
• 不足3条：衰弱前期
• 0条：无衰弱健康老人
`;
}

// 生成CSV数据
function generateCSVData(surveys) {
    let csvContent = '问答编号,记录时间,记录人,被评估人,年龄,性别,身高(cm),体重(kg),BMI,体重下降,行走时间(秒),握力(kg),体力活动(kcal/周),疲乏1,疲乏2,总分,诊断结果,备注\n';

    surveys.forEach(survey => {
        const bmi = survey.weight / Math.pow(survey.height / 100, 2);
        csvContent += `${survey.surveyId},${survey.recordTime},${survey.recorderName},${survey.patientName},${survey.age},${survey.gender === 'male' ? '男' : '女'},${survey.height},${survey.weight},${bmi.toFixed(1)},${survey.weightLoss === 'yes' ? '是' : '否'},${survey.walkTime},${survey.gripStrength},${survey.physicalActivity},${survey.fatigue1},${survey.fatigue2},${survey.totalScore},${survey.diagnosis},${survey.remarks || ''}\n`;
    });

    return csvContent;
}

// 生成个人报告
function generateIndividualReport(survey) {
    const bmi = survey.weight / Math.pow(survey.height / 100, 2);
    return `Fried衰弱评估个人报告
问答编号：${survey.surveyId}
评估时间：${survey.recordTime}

=== 记录人信息 ===
记录人：${survey.recorderName}
职务：${survey.recorderPosition}
机构：${survey.recorderInstitution || '未填写'}

=== 被评估人信息 ===
姓名：${survey.patientName}
年龄：${survey.age}岁
性别：${survey.gender === 'male' ? '男性' : '女性'}
身高：${survey.height}cm
体重：${survey.weight}kg
BMI：${bmi.toFixed(1)}
联系电话：${survey.phone || '未填写'}

=== 评估结果 ===
总分：${survey.totalScore}/5
诊断：${survey.diagnosis}

=== 原始数据 ===
体重下降：${survey.weightLoss === 'yes' ? '是' : '否'}
行走时间：${survey.walkTime}秒
握力：${survey.gripStrength}kg
体力活动：${survey.physicalActivity}kcal/周
疲乏评分1：${survey.fatigue1}分
疲乏评分2：${survey.fatigue2}分

备注：${survey.remarks || '无'}
`;
}

// 保存文件到@data文件夹
function saveFile(req, res) {
    try {
        const { filename, content, surveyId } = req.body;

        // 创建问答编号对应的文件夹
        const groupDir = path.join(REPORT_DIR, surveyId);
        if (!fs.existsSync(groupDir)) {
            fs.mkdirSync(groupDir, { recursive: true });
        }

        // 保存文件
        const filepath = path.join(groupDir, filename);
        fs.writeFileSync(filepath, content, 'utf8');

        console.log(`报告文件已保存: ${filepath}`);
        res.json({
            success: true,
            message: '文件保存成功',
            filepath: filepath
        });
    } catch (error) {
        console.error('保存文件失败:', error);
        res.status(500).json({ success: false, message: '保存文件失败' });
    }
}

module.exports = {
    saveSurvey,
    exportSurvey,
    saveFile
};
